import Skype4Py
import xmlrpclib
import win32gui
import win32con
import subprocess as subp

class SkypeEventListener :
	def __init__(self) :
		self.initVariable()
		self.proxy = xmlrpclib.ServerProxy('http://localhost:9991')
		pass

	def initVariable(self) :
		self.skype = Skype4Py.Skype()
		if(not self.skype.Client.IsRunning) :
			self.skype.Client.Start()
		
		self.skype.Attach()
		self.skype.OnCallStatus = self.onCall
		self.skype.SilentMode = True
		
	def getProcessByTitle(self, title ):
		hwnd = win32gui.FindWindowEx(0,0,0, title)
		return hwnd

	def showXBMC(self):
		hwnd = self.getProcessByTitle("XBMC Media Center")
		win32gui.ShowWindow(hwnd,win32con.SW_SHOWDEFAULT)
		win32gui.SetForegroundWindow(hwnd)

	def hideXBMC(self):
		hwnd = self.getProcessByTitle("XBMC Media Center")
		win32gui.ShowWindow(hwnd,win32con.SW_HIDE)
		win32gui.SetForegroundWindow(hwnd)
	
	def hideSkype(self):
		self.skype.SilentMode = True
		pass
	
	def onCall(self, call, status):
		self.call = call
		
		if status == "RINGGING" :
			caller = call.PartnerHandle
			type = call.Type
			if type != 'cltOutgoingP2P' :
				receive = self.proxy.sendCallRequest(caller)
				if(receive) :
					call.Answer()					
					self.hideXBMC()
				else :
					call.Finish()
			else :
				pass
				
		elif status == "FINISHED" :
			self.hideSkype()
			self.showXBMC()
			
	def forceFinish(self) :
		try :
			self.call.Finish()
		except :
			print 'no call event ..'
	
	def testSendCallRequest(self):
		result = self.proxy.sendCallRequest('wearetherock')
		print result
			
class WiiSignal :

	PREVIOUS_KEY = "RELEASE" 
	
	def __init__(self) :	
		wiiSignal = 'c:\\KXBMC\\csharp-wii\\WiiSignal.exe'
		self.proc = subp.Popen( wiiSignal , stdin=subp.PIPE, stdout=subp.PIPE, bufsize=0)

	def getSignal(self):
		signal = self.proc.stdout.readline().strip()
		return signal
		
	def isDuplicate(self, key):
		if WiiSignal.PREVIOUS_KEY == key:
			return True
		else:
			WiiSignal.PREVIOUS_KEY = key
			return False

#############################
# start here 
if __name__ == '__main__' :
	
	skype = SkypeEventListener()
	#wiisig = WiiSignal()
	
	skype.testSendCallRequest()
	skype.testSendCallRequest()
	
	'''
	while True :
		signal = wiisig.getSignal()
		if (wiisig.isDuplicate(signal)) :
			print "duplicate .."
			continue
		
		if signal == "HOME" :
			skype.forceFinish()
	'''
			
		